# -*- coding: utf-8 -*-
import hashlib
import re
import datetime
import time
import requests


def get_md5_str(str_parm):
    """将字符串转化成MD5字符串 相同的str只有一个md5字符串"""
    if isinstance(str_parm, str):
        str_parm = str_parm.encode("utf-8")
    m = hashlib.md5()
    m.update(str_parm)
    return m.hexdigest()


def get_num(value):
    """匹配' 2 收藏 '字符串中的数字,没有返回0"""
    matchObj = re.match(r'.*?(\d+).*', value)
    if matchObj:
        return int(matchObj.group(1))
    else:
        return 0


def get_date(str=datetime.datetime.now().strftime("%Y-%m-%d"), formate="%Y-%m-%d"):
    """
    :param str: 日期字符串2017-10-29
    :param formate: 默认值%Y-%m-%d
    :return: 日期对象,默认返回当前日期对象
    """
    return datetime.datetime.strptime(str, formate).date()


def get_datetime(str=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), formate="%Y-%m-%d %H:%M:%S"):
    """
    :param str: 日期字符串2017-10-29 10:10:10
    :param formate: 默认值%Y-%m-%d %H:%M:%S
    :return: 日期时间对象,默认返回当前日期时间对象
    """
    return datetime.datetime.strptime(str, formate)


def get_date_or_datetime_str(datetime_obj=datetime.datetime.now(), formate="%Y-%m-%d %H:%M:%S"):
    """
    :param datetime: 日期对象
    :param formate: 日期格式化,默认为%Y-%m-%d %H:%M:%S
    :return: 日期字符串,默认获取当前时间的日期字符串
    """
    return datetime_obj.strftime(formate)


def get_first_value_list(value):
    """ 获取list中第一个元素 """
    if len(value) == 0:
        return None
    else:
        return value[0]


def get_csrf(session, url, headers):
    """
    获取指定url页面中的xsrf值
    session = requests.session()
    """
    response = session.get(url, headers=headers)
    match_obj = re.search(r'.*name="_xsrf" value="(.*?)".*', response.text)
    if match_obj:
        return match_obj.group(1)
    else:
        return None


def is_login(session, url, headers):
    """
    请求需要登录验证的页面来判断是否登录
    session = requests.session()
    """
    r = session.get(url, headers=headers, allow_redirects=False)
    #通过私信判断用户是否登录
    if r.status_code == 302:
        return False
    else:
        return True


def get_captcha(session, captcha_url, headers):
    """
    获取知乎验证码图片，并手动输入
    https://www.zhihu.com/captcha.gif?r={0}&type=login&lang=cn
    """
    captcha_url = captcha_url.format(str(int(time.time()*1000)))
    r = session.get(captcha_url, headers=headers)
    with open("captcha.jpg", "wb") as f:
        f.write(r.content)
        f.close()
    from PIL import Image
    try:
        im = Image.open("captcha.jpg")
        im.show()
        im.close()
    except Exception as e:
        pass
    captcha = input("输入验证码！")
    return captcha

def ip_isAllow(ip, port):
    """
    判断ip是否有效
    """
    url = "https://www.baidu.com/"
    proxy_utl = "http://{0}:{1}".format(ip, port)
    proxy = {
        "http": proxy_utl
    }
    try:
        response = requests.get(url, proxies=proxy)
        code = response.status_code
        if code >= 200 and code <= 300:
            return True
        else:
            return False
    except Exception as e:
        return False


def get_suggests(index,info_tuple):
    """根据字符串生成搜索建议词数组"""
    from elasticsearch_dsl.connections import connections
    from Scrapy_Redis_Test.settings import ES_HOSTS
    es = connections.create_connection(hosts=ES_HOSTS, timeout=20)
    # es = connections.create_connection(JobboleArticleType._doc_type.using)
    used_word = set()
    suggests = []
    for text,weight in info_tuple:
        if text:
            #调用es的analyze接口分析字符串
            words = es.indices.analyze(index=index,analyzer="ik_max_word",params={"filter":["lowercase"]},body=text)
            analyzed_words = set([r["token"] for r in words["tokens"] if len(r["token"]) > 1])
            new_words = analyzed_words - used_word
        else:
            new_words = set()
        if new_words:
            suggests.append({"input":list(new_words),"weight":weight})
    return suggests


def scrollBy(browser,time):
    """
    下拉到底部
    """
    browser.execute_script("var lenOfPage = document.body.scrollHeight; window.scrollBy(0,lenOfPage); return lenOfPage;")
    browser.implicitly_wait(time)

if __name__ == "__main__":
    pass
    # a = get_suggests("jobbole",(("python项目开发",10),("Java项目开发",8)))
    # print(a)